package com.hmy.pig.controller;

import com.alibaba.excel.EasyExcel;

import com.hmy.pig.domain.HmyPig;
import com.hmy.pig.listener.ExcelListener;
import com.hmy.pig.service.PigService;
import com.hmy.pig.service.impl.HmyPigServiceImpl;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
*  * @param null
* @return
* @author kdq
* @date 2024/2/20 18:04
* @description 批量插入猪只档案
*/

@RestController
@RequestMapping("/pig")
public class ExcelController{

    @Autowired
    private  HmyPigServiceImpl hmyPigService;

    @Autowired
    private ExcelListener excelListener;

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file){
        System.out.println("进入文件上传controller");
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream);//获取第一行数据
            Sheet sheet = workbook.getSheetAt(0); // 假设只有一个 sheet
            if (sheet == null || sheet.getLastRowNum() <= 0) {
                return AjaxResult.error("上传失败：文件内容为空");
            }
            EasyExcel.read(file.getInputStream(), HmyPig.class, new ExcelListener(hmyPigService)).sheet().doRead();
            return AjaxResult.success("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    /**
     *  * @param null
     * @return
     * @author kdq
     * @date 2024/2/21 14:45
     * @description 猪只档案导出
     */

    @GetMapping("/export")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        try {
            // 设置响应头信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            long curr = System.currentTimeMillis();
            hmyPigService.export();
            System.out.println(System.currentTimeMillis()-curr);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常
        }
    }
}
